require('dotenv').config();
const express = require('express');
const axios = require('axios');
const cors = require('cors');
const weatherRoute = require('./routes/weather.route');

const app = express();

// 配置CORS
app.use(cors({
  origin: ['http://localhost:5174', 'http://localhost:5173'], // 允许的前端域名
  methods: ['GET', 'POST', 'OPTIONS'],
  allowedHeaders: ['Content-Type', 'Authorization'],
  credentials: true
}));

app.use(express.json());

// 挂载天气路由
console.log('正在挂载天气路由...');
app.use('/api/weather', weatherRoute);
console.log('天气路由挂载完成');

// 添加一个测试路由
app.get('/api/test', (req, res) => {
  res.json({ message: 'API服务器正常运行' });
});

// 错误处理中间件
app.use((err, req, res, next) => {
  console.error('服务器错误:', err);
  res.status(500).json({
    code: 500,
    message: '服务器内部错误'
  });
});

// 高德地图天气 API 配置
const AMAP_WEATHER_URL = process.env.AMAP_WEATHER_URL;
const AMAP_API_KEY = process.env.AMAP_API_KEY;
// 打印高德 API 配置信息
console.log('AMAP_WEATHER_URL:', AMAP_WEATHER_URL);
console.log('AMAP_API_KEY:', AMAP_API_KEY);

// 数据格式化函数
const normalizeAmapData = (data) => {
  if (!data.lives || data.lives.length === 0) {
    throw new Error('未找到天气信息');
  }
  const weather = data.lives[0];
  return {
    city: weather.city,
    temp: parseFloat(weather.temperature),
    humidity: parseFloat(weather.humidity),
    wind: weather.winddirection + ' ' + weather.windpower + '级',
    weatherDesc: weather.weather,
    icon: weather.weatherIconUrl || '',
    reportTime: weather.reporttime
  };
};


// 路由定义
app.get('/api/weather', async (req, res) => {
  try {
    const { city } = req.query;

    const response = await axios.get(AMAP_WEATHER_URL, {
      params: {
        key: AMAP_API_KEY,
        city: city,
        extensions: 'base'
      }
    });

    console.log('原始返回:', response.data);

    if (response.data.status === '0') {
      throw new Error(`高德API错误: ${response.data.info}`);
    }

    if (!response.data.lives || response.data.lives.length === 0) {
      throw new Error(`未找到 "${city}" 的天气信息`);
    }

    res.json(normalizeAmapData(response.data));
  } catch (error) {
    console.error('请求高德天气失败:', error.response?.data || error.message);
    res.status(500).json({ error: '获取天气数据失败' });
  }
});

module.exports = app;